package com.example.run_game;

import java.io.File;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.example.run_game.PostRunInformation.SectionsPagerAdapter;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.SupportMapFragment;

import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;

import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;

import android.graphics.Bitmap;
import android.provider.MediaStore;

import android.util.Log;

import android.view.View;
import android.view.View.OnClickListener;

import android.location.Location;
import android.net.Uri;

import android.os.Bundle;
import android.os.Environment;

import android.widget.Button;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView;

public class PlayerProfile extends Activity {
	
	private Uri mImageCaptureUri;
	private ImageView mImageView;
	private Player mPlayer;
	private DbManager db;

	private static final int PICK_FROM_CAMERA = 1;
	private static final int CROP_FROM_CAMERA = 2;
	private static final int PICK_FROM_FILE = 3;
	
	Dialog dialogEditProfile;
	Dialog dialogEditInfo;
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_player_profile); 
        
        db = new DbManager(this);
        mPlayer = new Player(db);
        Log.d("Player Profile", "DB Connection Made");   
        //syncStuff();
        populateInfo();
        
        Button achievementsButton = (Button)findViewById(R.id.btnAchievements);
		achievementsButton.setOnClickListener(checkAchievementsPress);
		Button historyButton = (Button)findViewById(R.id.btnHistory);
		historyButton.setOnClickListener(checkHistoryPress);
		
		//Create a custom dialog for when the edit profile button is pressed
        dialogEditProfile = new Dialog(this);
        dialogEditProfile.setContentView(R.layout.dialog_edit_profile);
        dialogEditProfile.setTitle("Edit Profile");
        
        //Create a custom dialog for when edit personal info is pressed
        dialogEditInfo = new Dialog(this);
        dialogEditInfo.setContentView(R.layout.dialog_edit_info);
        dialogEditInfo.setTitle("Edit Info");
        
        final String [] items			= new String [] {"Take from camera", "Select from gallery"};				
		ArrayAdapter<String> adapter	= new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
		AlertDialog.Builder builder		= new AlertDialog.Builder(this);

		builder.setTitle("Select Image");
		builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
			public void onClick( DialogInterface dialog, int item ) { //pick from camera
				if (item == 0) {
					Intent intent 	 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

					mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
									   "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));

					intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);

					try {
						intent.putExtra("return-data", true);

						startActivityForResult(intent, PICK_FROM_CAMERA);
					} catch (ActivityNotFoundException e) {
						e.printStackTrace();
					}
				} else { //pick from file
					Intent intent = new Intent();

	                intent.setType("image/*");
	                intent.setAction(Intent.ACTION_GET_CONTENT);

	                startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
				}
			}
		} );

		final AlertDialog dialog = builder.create();

		Button button 	= (Button) findViewById(R.id.btnGallery);
		mImageView		= (ImageView) findViewById(R.id.profile_picture);

		button.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View v) {
				
				Button infoButton = (Button)dialogEditProfile.findViewById(R.id.edit_info);
		        infoButton.setOnClickListener(checkEditInfoPress);
		        
		        Button photoButton = (Button)dialogEditProfile.findViewById(R.id.edit_photo);
		        photoButton.setOnClickListener(new View.OnClickListener() {
		        	@Override
					public void onClick(View v) {
		        		dialogEditProfile.dismiss();
		        		dialog.show();
		        	}
		        });
		        			        
		        dialogEditProfile.show();
			}
		});
		setupProgressBar();
    }
    
    private void syncStuff()
	{
		double dist = Utils.totalDistanceEver(getApplicationContext());
		long time	= Utils.totalTimeEver(getApplicationContext());
		int numRuns = Utils.totalNumberRuns(getApplicationContext());
		mPlayer.setTotalDistance(dist);
		mPlayer.setTotalTime(time);
		mPlayer.setTotalRuns(numRuns);
		mPlayer.setAvSpeed((1.0*dist)/(time/1000));
		mPlayer.setAvTime((long)1.0*time/numRuns);
		mPlayer.setAvDistance(dist/numRuns);
		mPlayer.setTotalCaloriesBurned(Utils.calcCalories(dist, (int)mPlayer.getWeight()));
		mPlayer.setXPLevel(0, 1);
		mPlayer.awardXP((int)(dist*2.107));
		System.out.println("avtime:"+1.0*time/numRuns + " time:"+time+" numruns:"+numRuns);
		mPlayer.save();
	}

	private void populateInfo()
	{
    	String updateText = "";
    	
    	Bitmap picture = mPlayer.getPicture();
    	mImageView = (ImageView) findViewById(R.id.profile_picture);
    	if(picture != null)
    		mImageView.setImageBitmap(picture);
    	
    	
    	TextView name = (TextView) findViewById(R.id.player_name);
    	updateText = mPlayer.getName();
    	name.setText(updateText);
    	
    	TextView weight	= (TextView) findViewById(R.id.weight_val);
    	updateText = Double.toString(mPlayer.getWeight()) + "kg";
    	weight.setText(updateText);
    	
    	TextView height	= (TextView) findViewById(R.id.height_val);
    	updateText = Double.toString(mPlayer.getHeight()) + "m";
    	height.setText(updateText);
    	
    	TextView calories	= (TextView) findViewById(R.id.calories_val);
    	updateText = Integer.toString(mPlayer.getTotalCaloriesBurned());
    	calories.setText(updateText);
    	
    	TextView runs	= (TextView) findViewById(R.id.total_runs_val);
    	updateText = Integer.toString(mPlayer.getTotalRuns());
    	runs.setText(updateText);  	
	
    	TextView disttime	= (TextView) findViewById(R.id.total_dist_val);
    	DecimalFormat df = new DecimalFormat("#.##");
    	disttime.setText(df.format(mPlayer.getTotalDistance()/1000)+"km");
    	
    	TextView uphill	= (TextView) findViewById(R.id.total_time_val);
    	updateText = Utils.formatMilliTime(mPlayer.getTotalTime(),false);
    	uphill.setText(updateText);
    	
    	TextView avspeed	= (TextView) findViewById(R.id.avg_speed_val);
    	updateText = "" + df.format(mPlayer.getAvSpeed()*60*60/1000)+"kph";
    	avspeed.setText(updateText);
    	
    	TextView avdist	= (TextView) findViewById(R.id.avg_distance_val);
    	updateText = df.format(mPlayer.getAvDistance()/1000) + "km";
    	avdist.setText(updateText);
    	
    	TextView avtime	= (TextView) findViewById(R.id.avg_time_val);
    	updateText = Utils.formatMilliTime(mPlayer.getAvTime(),false);
    	avtime.setText(updateText);

	}
    
    private String convertTimeString(int totalSeconds){
    	
    	int hr = totalSeconds/3600;
		String h = hr<10?"0"+hr:hr==0?"00":hr+"";
		int m = (totalSeconds%3600)/60;
		int s = totalSeconds%60;
		String timeString = h+":"+m+":"+s;
		
    	return timeString;
    }
    
    private OnClickListener checkAchievementsPress = new OnClickListener() 
    {
		public void onClick(View v) 
		{
			Intent intent = new Intent(getBaseContext(), AchievementCentre.class);
			startActivity(intent);
		}
    };
    
    private OnClickListener checkHistoryPress = new OnClickListener() 
    {
		public void onClick(View v) 
		{
			Intent intent = new Intent(getBaseContext(),RunHistory.class);
			startActivity(intent);
		}
    };
    
     
    
    /* Checks if the Edit Information option is selected.
     * Creates buttons/listeners for the edit info dialog Cancel and Go buttons
     */
    private OnClickListener checkEditInfoPress = new OnClickListener() 
    {
		public void onClick(View v) 
		{
			
			Button saveButton = (Button)dialogEditInfo.findViewById(R.id.save);
	        saveButton.setOnClickListener(savePlayerInfo);
	        
	        Button cancelButton = (Button)dialogEditInfo.findViewById(R.id.cancel);
	        cancelButton.setOnClickListener(closeInfoDia);
	        
	        EditText editName = (EditText)dialogEditInfo.findViewById(R.id.name_val);
	        editName.setText((mPlayer.getName()).toString());
	        
	        EditText editWeight = (EditText)dialogEditInfo.findViewById(R.id.weight_val);
	        editWeight.setText(Double.toString(mPlayer.getWeight()));
	        
	        EditText editHeight = (EditText)dialogEditInfo.findViewById(R.id.height_val);
	        editHeight.setText(Double.toString(mPlayer.getHeight()));
	        
	        dialogEditProfile.dismiss();
	        dialogEditInfo.show();
		}
    };
    
    private OnClickListener savePlayerInfo = new OnClickListener() 
    {
		public void onClick(View v) 
		{
			EditText name = (EditText)dialogEditInfo.findViewById(R.id.name_val);
			EditText weight = (EditText)dialogEditInfo.findViewById(R.id.weight_val);
			EditText height = (EditText)dialogEditInfo.findViewById(R.id.height_val);
			
			mPlayer.setName((name.getText()).toString());
			mPlayer.setWeight(Double.parseDouble((weight.getText()).toString()));
			mPlayer.setHeight(Double.parseDouble((height.getText()).toString()));
			mPlayer.save();			
			populateInfo();
			dialogEditInfo.dismiss();
		}
	};
	
	private OnClickListener closeInfoDia = new OnClickListener() 
    {
		public void onClick(View v) 
		{
			dialogEditInfo.dismiss();		
		}		   
	};

    
    /*
     * Code below handles the camera picture and cropping
     */

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode != RESULT_OK) return;

	    switch (requestCode) {
		    case PICK_FROM_CAMERA:
		    	doCrop();
		    	System.out.println("PICKFROMCAMERA/n");
		    	break;

		    case PICK_FROM_FILE: 
		    	mImageCaptureUri = data.getData();
		    	System.out.println("PICKFROMFILE/n");
		    	doCrop();

		    	break;	    	

		    case CROP_FROM_CAMERA:	    	
		        Bundle extras = data.getExtras();
		        System.out.println("CROPFROMCAMERA/n");
		        if (extras != null) {	        	
		            Bitmap photo = extras.getParcelable("data");
		            //mImageView.setImageURI(mImageCaptureUri);
		            mImageView.setImageBitmap(photo);
		            mPlayer.setPicture(photo);
		            mPlayer.save();
		        }

		        if (mImageCaptureUri != null)
		        {
			        File f = new File(mImageCaptureUri.getPath());   
			        
			        System.out.println(mImageCaptureUri);

			        if (f.exists()) f.delete();
		        }

		        break;

	    }
	}
    
    private void doCrop() {
		final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
    	
    	Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setType("image/*");
        
        List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
        
        int size = list.size();
        
        if (size == 0) {	        
        	Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
        	
            return;
        } else {
        	intent.setData(mImageCaptureUri);
            
            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("scale", true);
            intent.putExtra("return-data", true);
            
        	if (size == 1) {
        		Intent i 		= new Intent(intent);
	        	ResolveInfo res	= list.get(0);

	        	i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

	        	startActivityForResult(i, CROP_FROM_CAMERA);
        	} else {
		        for (ResolveInfo res : list) {
		        	final CropOption co = new CropOption();

		        	co.title 	= getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
		        	co.icon		= getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
		        	co.appIntent= new Intent(intent);

		        	co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

		            cropOptions.add(co);
		        }

		        CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);

		        AlertDialog.Builder builder = new AlertDialog.Builder(this);
		        builder.setTitle("Choose Crop App");
		        builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
		            public void onClick( DialogInterface dialog, int item ) {
		                startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
		            }
		        });

		        builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
		            @Override
		            public void onCancel( DialogInterface dialog ) {

		                if (mImageCaptureUri != null ) {
		                    getContentResolver().delete(mImageCaptureUri, null, null );
		                    mImageCaptureUri = null;
		                }
		            }
		        } );

		        AlertDialog alert = builder.create();

		        alert.show();
        	}
        }
	}
    
    protected void setupProgressBar()
	{	       
		DbManager db = new DbManager(this);
		Player player = new Player(db);
		int percentage = player.getProgressBarPercentage();
		int lvl = player.getLevel();	 
				
		((ProgressBar)findViewById (R.id.progressBar)).setProgress(percentage);			
		((TextView)findViewById (R.id.level_lower_text)).setText(""+lvl);		
		((TextView)findViewById (R.id.level_upper_text)).setText(""+(lvl+1));
	}
}
